package com.example.dnfgamercommunitybackend.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {
    //声明签名
    final String signature = "dnf@player.666";
    public String createToken(int id){

        //声明失效时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,24);


        //JWT头部信息
        Map<String, Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");

        //载荷
        Map<String, Object> payload = new HashMap<>();
        payload.put("id",id);

        return Jwts.builder()
                .setHeader(header)
                .setClaims(payload)
                .setExpiration(calendar.getTime())
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
    }

    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try{
            claims = Jwts
                        .parser()
                        .setSigningKey(signature)
                        .parseClaimsJws(token)
                        .getBody();
        }catch (Exception e){
            throw new RuntimeException("token解析失败");
        }
        return claims;
    }

    public String getUserIdFromToken(String token) {
        return getClaimsFromToken(token).get("id").toString();
    }
}
